package sin;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CountWithExecutorService implements SumCountable {
	@SuppressWarnings("unchecked")
	public double sumcount(int nThreads, int n) {
		
		ExecutorService exec = Executors.newFixedThreadPool(nThreads);
		Callable<Double>[] tasks = TasksDisturber.getTasks(nThreads, n);
		Future<Double>[] future = new Future[nThreads];
		for (int i=0; i<nThreads; i++) {
			future[i] = exec.submit(tasks[i]);
		}
		
		double sum=0;
		
		for (int i=0; i<nThreads; i++) {
			try {
				sum+=future[i].get();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
		
		exec.shutdown();
		
		return sum;
	}
}
